<template>
  <div class="video-plate">
    <div class="video-body" id="video-body">
      <div class="box-row row-3" :class="{'hiddenOthers': hiddenVideos}">
        <div class="box-col-1 item-3" :class="{'hiddenVideos': hiddenVideos}">
          <div class="item-row-1 left top">
            <div id="videoItem0" class="video-item" v-loading="loading0" element-loading-text="正在连接..."
              element-loading-spinner="el-icon-loading" element-loading-background="#000000" @drop="drop($event, 0)"
              @dragover.prevent>
              <video-box ref="videoBox0" video-index="0" :loading.sync="loading0" @videoDistribution="videoDistribution"
                @videoExit="videoExit"></video-box>
            </div>
          </div>
          <div class="item-row-1 left">
            <div id="videoItem2" class="video-item" v-loading="loading2" element-loading-text="正在连接..."
              element-loading-spinner="el-icon-loading" element-loading-background="#000000" @drop="drop($event, 2)"
              @dragover.prevent>
              <video-box ref="videoBox2" video-index="2" :loading.sync="loading2" @videoDistribution="videoDistribution"
                @videoExit="videoExit"></video-box>
            </div>
          </div>
          <div class="item-row-1 left">
            <div id="videoItem4" class="video-item" v-loading="loading4" element-loading-text="正在连接..."
              element-loading-spinner="el-icon-loading" element-loading-background="#000000" @drop="drop($event, 4)"
              @dragover.prevent>
              <video-box ref="videoBox4" video-index="4" :loading.sync="loading4" @videoDistribution="videoDistribution"
                @videoExit="videoExit"></video-box>
            </div>
          </div>
        </div>
        <div class="box-col-3 mix" :class="{'hiddenOthers': hiddenVideos}">
          <div id="videoItemMix" class="video-item video-item-mix" ref="video-item-mix" v-loading="loadingMix"
            element-loading-text="正在连接..." element-loading-spinner="el-icon-loading"
            element-loading-background="#000000" @drop="dropMix($event)" @dragover.prevent>
            <video-box ref="videoBoxMix" video-index="Mix" size="medium" :loading.sync="loadingMix"
              :mixType.sync="mixType" @setMultiscreen="setMultiscreen" @setMixResolution="setMixResolution"
              @videoDistribution="videoDistribution" @deleteMixIndex="deleteMixIndex" @videoExit="videoExit">
            </video-box>
          </div>
        </div>
        <div class="box-col-1 item-3" :class="{'hiddenVideos': hiddenVideos}">
          <div class="item-row-1 right top">
            <div id="videoItem1" class="video-item" v-loading="loading1" element-loading-text="正在连接..."
              element-loading-spinner="el-icon-loading" element-loading-background="#000000" @drop="drop($event, 1)"
              @dragover.prevent>
              <video-box ref="videoBox1" video-index="1" :loading.sync="loading1" @videoDistribution="videoDistribution"
                @videoExit="videoExit"></video-box>
            </div>
          </div>
          <div class="item-row-1 right">
            <div id="videoItem3" class="video-item" v-loading="loading3" element-loading-text="正在连接..."
              element-loading-spinner="el-icon-loading" element-loading-background="#000000" @drop="drop($event, 3)"
              @dragover.prevent>
              <video-box ref="videoBox3" video-index="3" :loading.sync="loading3" @videoDistribution="videoDistribution"
                @videoExit="videoExit"></video-box>
            </div>
          </div>
          <div class="item-row-1 right">
            <div id="videoItem5" class="video-item" v-loading="loading5" element-loading-text="正在连接..."
              element-loading-spinner="el-icon-loading" element-loading-background="#000000" @drop="drop($event, 5)"
              @dragover.prevent>
              <video-box ref="videoBox5" video-index="5" :loading.sync="loading5" @videoDistribution="videoDistribution"
                @videoExit="videoExit"></video-box>
            </div>
          </div>
        </div>
      </div>
      <div class="box-row row-1" :class="{'hiddenVideos': hiddenVideos}">
        <div class="box-col-1 left">
          <div id="videoItem6" class="video-item" v-loading="loading6" element-loading-text="正在连接..."
            element-loading-spinner="el-icon-loading" element-loading-background="#000000" @drop="drop($event, 6)"
            @dragover.prevent>
            <video-box ref="videoBox6" video-index="6" :loading.sync="loading6" @videoDistribution="videoDistribution"
              @videoExit="videoExit"></video-box>
          </div>
        </div>
        <div class="box-col-1 between">
          <div id="videoItem7" class="video-item" v-loading="loading7" element-loading-text="正在连接..."
            element-loading-spinner="el-icon-loading" element-loading-background="#000000" @drop="drop($event, 7)"
            @dragover.prevent>
            <video-box ref="videoBox7" video-index="7" :loading.sync="loading7" @videoDistribution="videoDistribution"
              @videoExit="videoExit"></video-box>
          </div>
        </div>
        <div class="box-col-1 middle">
          <div id="videoItem8" class="video-item" v-loading="loading8" element-loading-text="正在连接..."
            element-loading-spinner="el-icon-loading" element-loading-background="#000000" @drop="drop($event, 8)"
            @dragover.prevent>
            <video-box ref="videoBox8" video-index="8" :loading.sync="loading8" @videoDistribution="videoDistribution"
              @videoExit="videoExit"></video-box>
          </div>
        </div>
        <div class="box-col-1 between">
          <div id="videoItem9" class="video-item" v-loading="loading9" element-loading-text="正在连接..."
            element-loading-spinner="el-icon-loading" element-loading-background="#000000" @drop="drop($event, 9)"
            @dragover.prevent>
            <video-box ref="videoBox9" video-index="9" :loading.sync="loading9" @videoDistribution="videoDistribution"
              @videoExit="videoExit"></video-box>
          </div>
        </div>
        <div class="box-col-1 right">
          <div id="videoItem10" class="video-item" v-loading="loading10" element-loading-text="正在连接..."
            element-loading-spinner="el-icon-loading" element-loading-background="#000000" @drop="drop($event, 10)"
            @dragover.prevent>
            <video-box ref="videoBox10" video-index="10" :loading.sync="loading10"
              @videoDistribution="videoDistribution" @videoExit="videoExit"></video-box>
          </div>
        </div>
      </div>
      <div class="box-row row-1" :class="{'hiddenVideos': hiddenVideos}">
        <div class="box-col-1 left">
          <div id="videoItem11" class="video-item" v-loading="loading11" element-loading-text="正在连接..."
            element-loading-spinner="el-icon-loading" element-loading-background="#000000" @drop="drop($event, 11)"
            @dragover.prevent>
            <video-box ref="videoBox11" video-index="11" :loading.sync="loading11"
              @videoDistribution="videoDistribution" @videoExit="videoExit"></video-box>
          </div>
        </div>
        <div class="box-col-1 between">
          <div id="videoItem12" class="video-item" v-loading="loading12" element-loading-text="正在连接..."
            element-loading-spinner="el-icon-loading" element-loading-background="#000000" @drop="drop($event, 12)"
            @dragover.prevent>
            <video-box ref="videoBox12" video-index="12" :loading.sync="loading12"
              @videoDistribution="videoDistribution" @videoExit="videoExit"></video-box>
          </div>
        </div>
        <div class="box-col-1 middle">
          <div id="videoItem13" class="video-item" v-loading="loading13" element-loading-text="正在连接..."
            element-loading-spinner="el-icon-loading" element-loading-background="#000000" @drop="drop($event, 13)"
            @dragover.prevent>
            <video-box ref="videoBox13" video-index="13" :loading.sync="loading13"
              @videoDistribution="videoDistribution" @videoExit="videoExit"></video-box>
          </div>
        </div>
        <div class="box-col-1 between">
          <div id="videoItem14" class="video-item" v-loading="loading14" element-loading-text="正在连接..."
            element-loading-spinner="el-icon-loading" element-loading-background="#000000" @drop="drop($event, 14)"
            @dragover.prevent>
            <video-box ref="videoBox14" video-index="14" :loading.sync="loading14"
              @videoDistribution="videoDistribution" @videoExit="videoExit"></video-box>
          </div>
        </div>
        <div class="box-col-1 right">
          <div id="videoItem15" class="video-item" v-loading="loading15" element-loading-text="正在连接..."
            element-loading-spinner="el-icon-loading" element-loading-background="#000000" @drop="drop($event, 15)"
            @dragover.prevent>
            <video-box ref="videoBox15" video-index="15" :loading.sync="loading15"
              @videoDistribution="videoDistribution" @videoExit="videoExit"></video-box>
          </div>
        </div>
      </div>
    </div>
    <div class="video-footer">
      <el-tooltip popper-class="video_plate" effect="light" :content="hiddenVideos ? '显示视频' : '隐藏视频'" :hide-after="3000"
        :enterable="false" placement="top">
        <svg-icon :icon-class="hiddenVideos ? 'show' : 'hide'" @click="hiddenVideos = !hiddenVideos"></svg-icon>
      </el-tooltip>
      <el-tooltip popper-class="video_plate" effect="light" content="全屏" :hide-after="3000" :enterable="false"
        placement="top">
        <svg-icon icon-class="fullscreen4" @click="playFullscreen('video-body')"></svg-icon>
      </el-tooltip>
      <el-tooltip popper-class="video_plate" effect="light" content="全部停止" :hide-after="3000" :enterable="false"
        placement="top">
        <svg-icon icon-class="stop-all" @click="destroyExit()"></svg-icon>
      </el-tooltip>
    </div>
    <!-- 视频分发窗口 -->
    <distribution v-if="openDistribution" :open.sync="openDistribution" :source="distributionSource"></distribution>
  </div>
</template>

<script>
import screenfull from 'screenfull'
import playRtsp from '@/utils/webrtc2rtsp'

import Distribution from './Distribution'
import VideoBox from './VideoBox'

export default {
  name: 'DriveVideo',
  props: {
    open: Boolean,
    meeting: Object,
    operatorCallTels: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    VideoBox,
    Distribution,
  },
  data() {
    return {
      srcArray: [
        {
          src: '',
          videoID: '',
          flowID: '',
        },
        {
          src: '',
          videoID: '',
          flowID: '',
        },
        {
          src: '',
          videoID: '',
          flowID: '',
        },
        {
          src: '',
          videoID: '',
          flowID: '',
        },
        {
          src: '',
          videoID: '',
          flowID: '',
        },
        {
          src: '',
          videoID: '',
          flowID: '',
        },
        {
          src: '',
          videoID: '',
          flowID: '',
        },
        {
          src: '',
          videoID: '',
          flowID: '',
        },
        {
          src: '',
          videoID: '',
          flowID: '',
        },
        {
          src: '',
          videoID: '',
          flowID: '',
        },
        {
          src: '',
          videoID: '',
          flowID: '',
        },
        {
          src: '',
          videoID: '',
          flowID: '',
        },
        {
          src: '',
          videoID: '',
          flowID: '',
        },
        {
          src: '',
          videoID: '',
          flowID: '',
        },
        {
          src: '',
          videoID: '',
          flowID: '',
        },
        {
          src: '',
          videoID: '',
          flowID: '',
        },
      ],
      rtspNodes: [],

      loading0: false,
      loading1: false,
      loading2: false,
      loading3: false,
      loading4: false,
      loading5: false,
      loading6: false,
      loading7: false,
      loading8: false,
      loading9: false,
      loading10: false,
      loading11: false,
      loading12: false,
      loading13: false,
      loading14: false,
      loading15: false,
      loadingMix: false,

      calling: '', // 主叫号码
      mixSources: [],
      videoType: '720P',
      mixType: 1,
      showResolution: false,
      showDelMixTable: false,
      showMultiscreen: false,
      openDistribution: false,
      distributionSource: {},
      rtspNodeMix: {},

      hiddenVideos: false, // 隐藏视频
    }
  },
  methods: {
    // 回调事件
    event(e) {
      switch (e.type) {
        case 'meet_member_event':
          if (e.event === 'DelMeetMember') {
            // 删除
            this.delMixResource(e.user, e.meetID)
            for (let i = 0; i < this.srcArray.length; i++) {
              const video = this.srcArray[i]
              if (video.videoID === e.user) {
                this.videoExit(i)
                break
              }
            }
          } else if (e.event === 'NewMeetMember') {
            console.log('NewMeetMember -------NewMeetMember')
            sessionStorage.setItem(
              'meetingStarted-' + this.meeting.meetID,
              true
            )
            if (!this.calling)
              this.calling = sessionStorage.getItem(
                'meetingCalling-' + this.meeting.meetID
              )
            if (e.user === this.calling && e.meetID === this.meeting.meetID) {
              // 主叫号码
              if (this.mixSources.length === 0) {
                this.$set(this.mixSources, 0, {
                  calledDevice: this.calling,
                  nid: e.user,
                })
                this.mixVideo(1)
              } else if (this.mixSources.length <= this.mixType) {
                for (let i = 0; i < this.mixSources.length; i++) {
                  const src = this.mixSources[i]
                  if (!src || Object.keys(src)) {
                    this.$set(this.mixSources, i, {
                      nid: e.user,
                      calledDevice: this.calling,
                    })
                    this.mixVideo()
                    return
                  }
                }
                if (this.mixSources.length < this.mixType) {
                  this.$set(this.mixSources, this.mixSources.length, {
                    nid: e.user,
                    calledDevice: this.calling,
                  })
                  this.mixVideo()
                }
              }
            }
          }
          break
        case 'StartVideoDispense':
          this.dispenseEvent(e)
          break
        default:
          break
      }
    },
    // 打开联动摄像头
    openLinkedVideo(data) {
      if (
        this.srcArray.findIndex((item) => item.videoID === data.obj.videoID) !==
        -1
      ) {
        this.msgError('关联的摄像头已经打开')
        return
      }
      let index = this.srcArray.findIndex((item) => item.videoID === '')
      if (index === -1) {
        this.msgError('最多只能打开16方视频')
        return
      }
      this.drop('', index, data)
    },
    // 失败消息
    msgError(msg) {
      this.$message({
        message: msg || '操作失败',
        type: 'error',
        showClose: true,
        duration: 3 * 1000,
      })
    },
    // 视频分发事件
    dispenseEvent(e) {
      if (e.result === 'fail') {
        return this.msgError(`视频分发失败, ${e.reason}`)
      }
      let msgStr = sessionStorage.getItem(e.mesg_id)
      if (msgStr) {
        const dispenseData = JSON.parse(msgStr)
        dispenseData.flowID = e.eventdata.flowID
        let dispense = []
        let old = sessionStorage.getItem(
          `dispense-${dispenseData.calledDevice || dispenseData.videoID}`
        )
        if (old) dispense = JSON.parse(old)
        dispense.push(dispenseData)
        sessionStorage.setItem(
          `dispense-${dispenseData.calledDevice || dispenseData.videoID}`,
          JSON.stringify(dispense)
        )
        sessionStorage.removeItem(e.mesg_id)
      }
    },
    // 播放视频回调
    playVideoCallback({ data, event, elId }) {
      let index = elId.replace('video', '')
      if (data) {
        if (data.result !== 'succ') {
          this[`loading${index}`] = false
          if (index === 'Mix') {
            this.rtspNodeMix = null
          } else {
            const item = this.srcArray[index]
            this.$emit('updataTreeNode', {
              nid: item.nid,
              isPlaying: false,
            })
            let flag = false
            for (let i = 0; i < this.mixSources.length; i++) {
              const mix = this.mixSources[i]
              if (mix.calledDevice === item.videoID) {
                this.$set(this.mixSources, i, {})
                flag = true
                break
              }
            }
            this.$set(this.srcArray, index, {
              src: '',
              videoID: '',
              flowID: '',
            })
            this.rtspNodes[Number.parseInt(index)] = null
            this.updateLSVideoSrc()
            if (flag) this.mixVideo()
          }
        }
      } else if (event) {
        if (event.type === 'close') {
          this[`loading${index}`] = false
          if (index === 'Mix') {
            this.closeMixRtspNode()
          } else {
            this.closeSrcRtspNode(Number.parseInt(index))
          }
        }
      }
    },
    // 打开视频分发窗口
    videoDistribution(index) {
      if (index !== 'Mix')
        this.distributionSource = this.srcArray[Number.parseInt(index)]
      else {
        // 混码区
        this.distributionSource = {
          videoID: this.meeting.meetID,
          flowID: this.meeting.meetID,
        }
      }
      this.openDistribution = true
    },

    // 设置混码区分几屏
    setMultiscreen(mixType) {
      if (this.mixType === mixType) return
      this.mixType = mixType
      for (let i = mixType; i < this.mixSources.length; i++) {
        this.$emit('updataTreeNode', {
          nid: this.mixSources[i].nid,
          checked: false,
        })
      }
      this.mixVideo()
    },
    // 设置混码区分辨率
    setMixResolution(videoType) {
      if (this.videoType === videoType) return
      this.videoType = videoType
      this.mixVideo()
    },
    // 删除混码区对应的视频
    deleteMixIndex(index) {
      if (index >= this.mixSources.length || !this.mixSources[index]) return
      let src = this.mixSources[index]
      if (src.flowID) SDK.closeVideo(src.videoID, src.flowID)
      this.$delete(this.mixSources, index)
      this.mixVideo()
      this.$emit('updataTreeNode', {
        nid: src.nid,
        checked: false,
      })
    },
    // 关闭混码
    closeMix() {
      for (let i = 0; i < this.mixSources.length; i++) {
        this.$emit('updataTreeNode', {
          nid: this.mixSources[i].nid,
          checked: false,
        })
        if (this.mixSources[i].flowID)
          SDK.closeVideo(this.mixSources[i].videoID, this.mixSources[i].flowID)
      }
      this.mixSources = []
      sessionStorage.removeItem('meetingMixSources-' + this.meeting.meetID)
      this.closeMixRtspNode()
      this.closeMixdispense()
      this.mixVideo(1)
    },
    // 删除混码源
    delMixResource(user, meetID) {
      if (!user) return
      if (meetID === this.meeting.meetID) {
        for (let i = 0; i < this.mixSources.length; i++) {
          if (
            this.mixSources[i].calledDevice &&
            this.mixSources[i].calledDevice === user
          ) {
            this.$delete(this.mixSources, i)
            this.mixVideo()
            this.$emit('updataTreeNode', {
              nid: user,
              checked: false,
            })
            break
          }
        }
      }
    },
    // 删除混码源
    delMixResourceNoMix(user, meetID) {
      console.log('delMixResourceNoMix', user, meetID, this.mixSources)
      if (!user) return
      if (meetID === this.meeting.meetID) {
        for (let i = 0; i < this.mixSources.length; i++) {
          if (
            this.mixSources[i].calledDevice &&
            this.mixSources[i].calledDevice === user
          ) {
            this.$set(this.mixSources, i, {})

            let form = {
              meetID: meetID,
              mixType: this.mixType,
              videoType: this.videoType,
              sources: this.mixSources,
            }
            if (
              sessionStorage.getItem(
                'meetingStarted-' + this.meeting.meetID
              ) === 'true'
            ) {
              sessionStorage.setItem(
                'meetingMixSources-' + meetID,
                JSON.stringify(form)
              )
            }
            console.log('delMixResourceNoMix end', JSON.stringify(form))
            break
          }
        }
      }
    },
    // 退出混码区视频分发
    closeMixdispense() {
      let old = sessionStorage.getItem(`dispense-${this.meeting.meetID}`)
      if (old) {
        let datas = JSON.parse(old)
        datas.forEach((item) => {
          let form = {
            flowID: item.flowID,
            videoID: this.meeting.meetID,
          }
          SDK.stopVideoDispense(form)
        })
        sessionStorage.removeItem(`dispense-${this.meeting.meetID}`)
      }
    },
    // 关闭会议处理
    closeMeeting() {
      this.mixType = 1
      this.destroyExit()
      for (let i = 0; i < this.mixSources.length; i++) {
        this.$emit('updataTreeNode', {
          nid: this.mixSources[i].nid,
          checked: false,
        })
        if (this.mixSources[i].flowID)
          SDK.closeVideo(this.mixSources[i].videoID, this.mixSources[i].flowID)
        this.$delete(this.mixSources, i)
      }
      this.closeMixRtspNode()
      this.closeMixdispense()

      this.loadingMix = false
      sessionStorage.removeItem('meetingStarted-' + this.meeting.meetID)
      sessionStorage.removeItem('meetingMixSources-' + this.meeting.meetID)
      sessionStorage.removeItem('meetingCalling-' + this.meeting.meetID)
      sessionStorage.removeItem('meetingVideoSrc-' + this.meeting.meetID)
    },
    checkMixVideo(node, checked) {
      let data = node.obj
      console.log('checkMixVideo', this.mixType, this.mixSources)
      if (this.mixSources > this.mixType) this.mixSources.splice(this.mixType)
      if (node.type === 'userVideo') {
        // 用户视频
        if (checked) {
          let emptyIndex = -1
          for (let i = 0; i < this.mixSources.length; i++) {
            if (
              this.mixSources[i].calledDevice &&
              data.activeDevice === this.mixSources[i].calledDevice
            ) {
              return
            }
            if (
              emptyIndex === -1 &&
              (!this.mixSources[i] ||
                Object.keys(this.mixSources[i]).length === 0)
            ) {
              emptyIndex = i
            }
          }
          if (emptyIndex === -1) {
            emptyIndex = this.mixSources.length
            if (emptyIndex === this.mixType) {
              switch (this.mixType) {
                case 1:
                  this.mixType = 2
                  break
                case 2:
                  this.mixType = 4
                  break
                case 4:
                  this.mixType = 6
                  break
                case 6:
                  this.mixType = 8
                  break
                case 8:
                  this.mixType = 9
                  break
                default:
                  break
              }
            }
          }
          this.$set(this.mixSources, emptyIndex, {
            calledDevice: data.activeDevice,
            nid: node.nid,
          })
          this.mixVideo()
        } else {
          for (let i = 0; i < this.mixSources.length; i++) {
            if (
              this.mixSources[i].calledDevice &&
              data.activeDevice === this.mixSources[i].calledDevice
            ) {
              this.$delete(this.mixSources, i)
              this.mixVideo()
              return
            }
          }
        }
      } else {
        // 摄像头混码
        if (checked) {
          let emptyIndex = -1
          for (let i = 0; i < this.mixSources.length; i++) {
            if (
              this.mixSources[i].videoID &&
              data.videoID === this.mixSources[i].videoID
            ) {
              return
            }
            if (
              emptyIndex === -1 &&
              (!this.mixSources[i] ||
                Object.keys(this.mixSources[i]).length === 0)
            ) {
              emptyIndex = i
            }
          }
          if (emptyIndex === -1) {
            emptyIndex = this.mixSources.length
            if (emptyIndex === this.mixType) {
              switch (this.mixType) {
                case 1:
                  this.mixType = 2
                  break
                case 2:
                  this.mixType = 4
                  break
                case 4:
                  this.mixType = 6
                  break
                case 6:
                  this.mixType = 8
                  break
                case 8:
                  this.mixType = 9
                  break
                default:
                  break
              }
            }
          }
          SDK.openVideo1(data.videoID)
            .then((res) => {
              this.$set(this.mixSources, emptyIndex, {
                videoID: data.videoID,
                nid: node.nid,
                flowID: res.flowID,
              })
              this.mixVideo()
            })
            .catch((res) => {
              this.msgError('打开摄像头失败')
              this.$emit('updataTreeNode', {
                nid: node.nid,
                checked: false,
              })
            })
        } else {
          for (let i = 0; i < this.mixSources.length; i++) {
            if (
              this.mixSources[i].videoID &&
              data.videoID === this.mixSources[i].videoID
            ) {
              if (this.mixSources[i].flowID)
                SDK.closeVideo(
                  this.mixSources[i].videoID,
                  this.mixSources[i].flowID
                )
              this.$delete(this.mixSources, i)
              this.mixVideo()
              return
            }
          }
        }
      }
    },
    // 获取播放状态
    getPlayStatus(calledDevice) {
      let isChecked = this.mixSources.some(
        (item) =>
          item.calledDevice === calledDevice || item.videoID === calledDevice
      )
      let playing = this.srcArray.some((item) => item.videoID === calledDevice)
      return {
        isChecked,
        playing,
      }
    },
    // 混码
    mixVideo(mixType, videoType) {
      console.log(
        'mixVideo rtspUrl=',
        this.meeting.rtspUrl,
        'mixType=',
        mixType ? mixType : this.mixType
      )
      mixType = mixType ? mixType : this.mixType
      if (this.mixSources.length > mixType) {
        this.mixSources.splice(mixType)
      }
      let form = {
        meetID: this.meeting.meetID,
        mixType: mixType,
        videoType: videoType ? videoType : this.videoType,
        sources: this.mixSources,
      }
      if (
        sessionStorage.getItem('meetingStarted-' + this.meeting.meetID) ===
        'true'
      ) {
        SDK.setMeetVideoMix(form)
        sessionStorage.setItem(
          'meetingMixSources-' + this.meeting.meetID,
          JSON.stringify(form)
        )
      }
      if (this.mixSources.length === 0) {
        this.closeMixRtspNode()
      } else if (
        !this.rtspNodeMix ||
        !this.rtspNodeMix.rtspNode ||
        this.rtspNodeMix.rtspUrl !== this.meeting.rtspUrl
      ) {
        let unempty = this.mixSources.some((item) => {
          return Object.keys(item).length === 0 ? false : true
        })
        if (unempty) {
          this.loadingMix = true
          this.rtspNodeMix = {
            rtspUrl: this.meeting.rtspUrl,
            rtspNode: playRtsp(
              this.meeting.rtspUrl,
              'videoMix',
              this.playVideoCallback
            ),
          }
        }
      } else {
        this.rtspNodeMix.rtspNode.RemoteVideo.play()
      }
    },
    initData(currentMeetingMembers = []) {
      this.rtspNodes.length = 16
      if (this.getLSVideoSrc()) {
        this.srcArray = JSON.parse(this.getLSVideoSrc())
        for (let i = 0; i < this.srcArray.length; i++) {
          const item = this.srcArray[i]
          if (!item.nid || !item.videoID) continue
          let flag = true
          if (item.type === 'userVideo') {
            let bool = false
            for (let j = 0; j < currentMeetingMembers.length; j++) {
              const m = currentMeetingMembers[j]
              if (item.videoID === m.activeDevice) {
                bool = false
                break
              }
            }
            if (bool) {
              // 删除
              this.$set(this.srcArray, i, {
                videoID: '',
                src: '',
                flowID: '',
              })
              this.$emit('updataTreeNode', {
                nid: item.nid,
                isPlaying: false,
              })
              if (this.rtspNodes[i]) {
                this.closeSrcRtspNode(i)
              }
            }
          }
          if (flag) {
            if (this.rtspNodes[i]) {
              this.rtspNodes[i].RemoteVideo.play()
            } else {
              this[`loading${i}`] = true
              this.rtspNodes[i] = playRtsp(
                item.src,
                `video${i}`,
                this.playVideoCallback
              )
            }
            this.$emit('updataTreeNode', {
              nid: item.nid,
              isPlaying: true,
            })
          }
        }

        this.updateLSVideoSrc()
      }
      // else if (currentMeetingMembers.length > 0) {
      //   currentMeetingMembers.forEach((item) => {
      //     console.log('initData 播放会议成员')
      //     if (item.rtspUrl) this.playMemberVideo(undefined, item)
      //   })
      // }
      this.calling = sessionStorage.getItem(
        'meetingCalling-' + this.meeting.meetID
      )
      // 混码区
      if (
        sessionStorage.getItem('meetingStarted-' + this.meeting.meetID) ===
        'true'
      ) {
        if (
          sessionStorage.getItem('meetingMixSources-' + this.meeting.meetID)
        ) {
          let mixForm = JSON.parse(
            sessionStorage.getItem('meetingMixSources-' + this.meeting.meetID)
          )
          let mixSources = mixForm.sources ? mixForm.sources : []
          for (let i = mixSources.length - 1; i >= 0; i--) {
            const item = mixSources[i]
            if (item.calledDevice) {
              let flag = true
              for (let j = 0; j < currentMeetingMembers.length; j++) {
                const m = currentMeetingMembers[j]
                if (item.calledDevice === m.activeDevice) {
                  flag = false
                  break
                }
              }
              if (flag) {
                mixSources.splice(i, 1)
              }
            } else {
              this.$emit('updataTreeNode', {
                nid: item.nid,
                checked: true,
              })
            }
          }
          this.mixSources = mixSources
          this.mixType = mixForm.mixType ? mixForm.mixType : 1
          this.videoType = mixForm.videoType ? mixForm.videoType : '720P'
          this.mixVideo(mixForm.mixType, mixForm.videoType)
        }
      }
    },

    getLSVideoSrc() {
      return sessionStorage.getItem('meetingVideoSrc-' + this.meeting.meetID)
    },
    updateLSVideoSrc() {
      sessionStorage.setItem(
        'meetingVideoSrc-' + this.meeting.meetID,
        JSON.stringify(this.srcArray)
      )
    },
    // 关闭除混码区的播放
    destroyExit() {
      for (let i = 0; i < this.srcArray.length; i++) {
        this.videoExit(i)
      }
    },
    // uncloseVideo为true时，不关闭摄像头
    async videoExit(index, uncloseVideo) {
      var value = this.srcArray[index]
      // 关闭视频
      this.closeSrcRtspNode(index)
      this.$set(this.srcArray, index, {
        src: '',
        videoID: '',
        flowID: '',
      })
      this[`loading${index}`] = false
      if (uncloseVideo !== true && value.flowID) {
        this[`show${index}`] = false
        await SDK.closeVideo(value.videoID, value.flowID)
      }
      this.updateLSVideoSrc()
      this.$emit('updataTreeNode', {
        nid: value.nid,
        isPlaying: false,
      })

      // 退出分发
      let old = sessionStorage.getItem(`dispense-${value.videoID}`)
      if (old) {
        let datas = JSON.parse(old)
        datas.forEach((item) => {
          let form = {
            flowID: item.flowID,
          }
          value.type === 'userVideo'
            ? (form.calledDevice = value.videoID)
            : (form.videoID = value.videoID)
          SDK.stopVideoDispense(form)
        })
        sessionStorage.removeItem(`dispense-${value.videoID}`)
      }
    },
    // 拖拽到混码区,触摸拖拽才有data参数
    dropMix(e, data) {
      if (
        sessionStorage.getItem('meetingStarted-' + this.meeting.meetID) !==
        'true'
      ) {
        this.$message({
          message: '请先发起会议',
          type: 'error',
          showClose: true,
          duration: 3 * 1000,
        })
        return
      }
      const node = data || JSON.parse(event.dataTransfer.getData('nodeData'))
      if (!this.isSupportVideoMode(node.obj)) {
        return
      }
      let el = this.$refs['video-item-mix']
      if (el) {
        const rect = el.getBoundingClientRect()
        const mouseRX = e.clientX - rect.x
        const mouseRY = e.clientY - rect.y
        let unitW, unitH, x, y
        let index = 0
        switch (this.mixType) {
          case 2:
            unitW = Math.ceil(rect.width / 2)
            x = Math.floor(mouseRX / unitW)
            index = x === 0 ? 0 : 1
            break
          case 4:
            unitW = Math.ceil(rect.width / 2)
            unitH = Math.ceil(rect.height / 2)
            x = Math.floor(mouseRX / unitW)
            y = Math.floor(mouseRY / unitH)
            if (x === 0) {
              index = y === 0 ? 0 : 2
            } else {
              index = y === 0 ? 1 : 3
            }
            break
          case 6:
            unitW = Math.ceil(rect.width / 3)
            unitH = Math.ceil(rect.height / 3)
            x = Math.floor(mouseRX / unitW)
            y = Math.floor(mouseRY / unitH)
            if (y === 0) {
              index = x !== 2 ? 0 : 1
            } else if (y === 1) {
              index = x !== 2 ? 0 : 2
            } else {
              index = x === 0 ? 3 : x === 1 ? 4 : 5
            }
            break
          case 8:
            unitW = Math.ceil(rect.width / 4)
            unitH = Math.ceil(rect.height / 4)
            x = Math.floor(mouseRX / unitW)
            y = Math.floor(mouseRY / unitH)
            if (y === 0) {
              index = x !== 3 ? 0 : 1
            } else if (y === 1) {
              index = x !== 3 ? 0 : 2
            } else if (y === 2) {
              index = x !== 3 ? 0 : 3
            } else {
              index = x === 0 ? 4 : x === 1 ? 5 : x === 2 ? 6 : 7
            }
            break
          case 9:
            unitW = Math.ceil(rect.width / 3)
            unitH = Math.ceil(rect.height / 3)
            x = Math.floor(mouseRX / unitW)
            y = Math.floor(mouseRY / unitH)
            if (x === 0) {
              index = y === 0 ? 0 : y === 1 ? 3 : 6
            } else if (x === 1) {
              index = y === 0 ? 1 : y === 1 ? 4 : 7
            } else {
              index = y === 0 ? 2 : y === 1 ? 5 : 8
            }
            break
          default:
            break
        }

        let obj = node.obj
        if (node.type === 'userVideo') {
          // 用户
          for (let i = 0; i < this.mixSources.length; i++) {
            const src = this.mixSources[i]
            if (src.calledDevice) {
              if (src.calledDevice === obj.activeDevice) {
                if (index === i) return
                else {
                  this.$set(this.mixSources, i, {})
                  break
                }
              }
            }
          }
          this.$set(this.mixSources, index, {
            calledDevice: obj.activeDevice,
          })
          this.mixVideo()
        } else {
          // 摄像头
          for (let i = 0; i < this.mixSources.length; i++) {
            const src = this.mixSources[i]
            if (src.videoID) {
              if (src.videoID === obj.videoID) {
                if (index === i) return
                else {
                  if (src.flowID) {
                    this.$set(this.mixSources, i, {})
                    let old = this.mixSources[index]
                    if (old.flowID) SDK.closeVideo(old.videoID, old.flowID)
                    this.$emit('updataTreeNode', {
                      nid: old.nid,
                      checked: false,
                    })
                    this.$set(this.mixSources, index, src)
                    this.mixVideo()
                    return
                  }
                  break
                }
              }
            }
          }
          let old = this.mixSources[index]
          this.$emit('updataTreeNode', {
            nid: old.nid,
            checked: false,
          })
          if (old.flowID) SDK.closeVideo(old.videoID, old.flowID)

          SDK.openVideo1(obj.videoID)
            .then((res) => {
              this.$set(this.mixSources, index, {
                videoID: obj.videoID,
                nid: node.nid,
                flowID: res.flowID,
              })
              this.mixVideo()
            })
            .catch((res) => {
              this.msgError('打开摄像头失败')
              this.$emit('updataTreeNode', {
                nid: node.nid,
                checked: false,
              })
            })
        }
      }
    },
    // 判断是否为支持混码
    isSupportVideoMode(camera) {
      if (camera.videoMode === '0') {
        this.$message({
          message: '不支持的摄像头类型',
          type: 'error',
          showClose: true,
          duration: 3 * 1000,
        })
        return false
      }
      return true
    },
    // 拖拽到非混码区,触摸拖拽才有data参数
    async drop(e, index, data) {
      if (
        sessionStorage.getItem('meetingStarted-' + this.meeting.meetID) !==
        'true'
      ) {
        this.$message({
          message: '请先发起会议',
          type: 'error',
          showClose: true,
          duration: 3 * 1000,
        })
        return
      }
      let node = data || JSON.parse(e.dataTransfer.getData('nodeData'))
      let obj = node.obj
      if (node.type === 'userVideo') {
        this.playMemberVideo(index, obj)
        return
      }

      let indexValue = this.srcArray[index]
      if (indexValue.videoID) {
        if (indexValue.videoID === obj.videoID) {
          this[`loading${index}`] = false
          return
        } else {
          await this.videoExit(index)
        }
      }
      this[`loading${index}`] = true
      for (let i = 0; i < this.srcArray.length; i++) {
        if (this.srcArray[i].videoID === obj.videoID) {
          if (i === index) {
            this[`loading${index}`] = false
            return
          }
          var oldValue = this.srcArray[i]
          // 关闭播放
          this.closeSrcRtspNode(i)
          this.$set(this.srcArray, i, {
            videoID: '',
            src: '',
            flowID: '',
          })
          this.$set(this.srcArray, index, oldValue)
          this.updateLSVideoSrc()
          this.rtspNodes[index] = playRtsp(
            oldValue.src,
            `video${index}`,
            this.playVideoCallback
          )
          this[`loading${index}`] = false
          this.$emit('updataTreeNode', {
            nid: node.nid,
            isPlaying: true,
          })
          return
        }
      }

      if (obj.videoMode === '0') {
        if (!obj.url) {
          this[`loading${index}`] = false
          return this.msgError('RTSP流地址不存在')
        }
        this.$set(this.srcArray, index, {
          nid: node.nid,
          videoID: obj.videoID,
          src: obj.url,
          flowID: '',
        })
        this.rtspNodes[index] = playRtsp(
          obj.url,
          `video${index}`,
          this.playVideoCallback
        )
      } else {
        SDK.openVideo1(obj.videoID)
          .then((res) => {
            this.$set(this.srcArray, index, {
              nid: node.nid,
              videoID: obj.videoID,
              src: res.rtspUrl,
              flowID: res.flowID,
            })
            this.updateLSVideoSrc()
            if (res.rtspUrl) {
              this.rtspNodes[index] = playRtsp(
                res.rtspUrl,
                `video${index}`,
                this.playVideoCallback
              )
            } else {
              this[`loading${index}`] = false
            }
          })
          .catch((err) => {
            console.log('openVideo1', err)
            this.msgError('打开摄像头失败')
            this[`loading${index}`] = false
          })
      }
      this.updateLSVideoSrc()
      this.$emit('updataTreeNode', {
        nid: node.nid,
        isPlaying: true,
      })
    },
    // 关闭视频播放
    closeSrcRtspNode(index) {
      if (this.rtspNodes[index]) {
        try {
          clearInterval(this.rtspNodes[index].Interval)
          this.rtspNodes[index].PC.close()
        } catch (error) {}
        this.rtspNodes[index] = null
      }
      if (this.$refs[`videoBox${index}`])
        this.$refs[`videoBox${index}`].closeControls()
    },
    // 关闭混码区视频播放
    closeMixRtspNode() {
      if (this.rtspNodeMix) {
        let rtspNode = this.rtspNodeMix.rtspNode
        try {
          clearInterval(rtspNode.Interval)
          rtspNode.PC.close()
        } catch (error) {}
        this.rtspNodeMix = null
        if (this.$refs.videoBoxMix) {
          this.$refs.videoBoxMix.closeControls()
        }
      }
    },
    // 播放会议成员视频
    playMemberVideo(index, data, isFirst) {
      if (index !== undefined) {
        for (let i = 0; i < this.srcArray.length; i++) {
          let old = this.srcArray[i]
          if (old.videoID === data.activeDevice) {
            if (i === index) return
            this.closeSrcRtspNode(i)
            this.$set(this.srcArray, i, {
              src: '',
              videoID: '',
              flowID: '',
            })
            this[`loading${i}`] = false
          }
        }

        this[`loading${index}`] = true
        let old = this.srcArray[index]
        this.$emit('updataTreeNode', {
          nid: old.nid,
          isPlaying: false,
        })
        this.closeSrcRtspNode(index)

        this.$set(this.srcArray, index, {
          src: data.rtspUrl,
          nid: data.activeDevice,
          videoID: data.activeDevice,
          flowID: '',
          type: 'userVideo',
        })
        this.rtspNodes[index] = playRtsp(
          data.rtspUrl,
          `video${index}`,
          this.playVideoCallback
        )
        this.$emit('updataTreeNode', {
          nid: data.activeDevice,
          isPlaying: true,
        })
        this.updateLSVideoSrc()
      } else {
        let tempIndex = -1
        for (let i = 0; i < this.srcArray.length; i++) {
          let src = this.srcArray[i]
          if (src.videoID === data.activeDevice) {
            if (this.rtspNodes[i]) return this.rtspNodes[i].RemoteVideo.play()
            else tempIndex = i
            break
          } else if (
            tempIndex === -1 &&
            src.videoID === '' &&
            src.flowID === ''
          ) {
            tempIndex = i
          }
        }
        if (tempIndex !== -1) {
          this.$set(this.srcArray, tempIndex, {
            nid: data.activeDevice,
            src: data.rtspUrl,
            videoID: data.activeDevice,
            flowID: '',
            type: 'userVideo',
          })
          this.rtspNodes[tempIndex] = playRtsp(
            data.rtspUrl,
            `video${tempIndex}`,
            this.playVideoCallback
          )
          this[`loading${tempIndex}`] = false
          this.updateLSVideoSrc()
          this.$emit('updataTreeNode', {
            nid: data.activeDevice,
            isPlaying: true,
          })
        }
      }
      // 第一次 进行混码
      if (isFirst) {
        console.error(
          '第一次 进行混码 1',
          data.activeDevice,
          this.operatorCallTels
        )
        if (
          !this.operatorCallTels ||
          this.operatorCallTels.length === 0 ||
          !this.operatorCallTels.includes(data.activeDevice)
        )
          return
        console.error('第一次 进行混码2')
        // 主叫号码
        if (this.mixSources.length === 0) {
          this.$set(this.mixSources, 0, {
            calledDevice: data.activeDevice,
            nid: data.activeDevice,
          })
          this.mixVideo(1)
        } else if (this.mixSources.length <= this.mixType) {
          for (let i = 0; i < this.mixSources.length; i++) {
            const src = this.mixSources[i]
            if (!src || Object.keys(src)) {
              this.$set(this.mixSources, i, {
                nid: data.activeDevice,
                calledDevice: data.activeDevice,
              })
              this.mixVideo()
              return
            }
          }
          if (this.mixSources.length < this.mixType) {
            this.$set(this.mixSources, this.mixSources.length, {
              nid: data.activeDevice,
              calledDevice: data.activeDevice,
            })
            this.mixVideo()
          }
        }
      }
    },
    // 混码摄像头
    mixOpenVideo(data) {
      for (let i = 0; i < this.mixSources.length; i++) {
        if (
          this.mixSources[i].videoID &&
          this.mixSources[i].videoID === data.videoID
        ) {
          let value = this.mixSources[i]
          value.flowID = data.flowID
          this.$set(this.mixSources, i, value)
          this.mixVideo()
          this.$emit('updataTreeNode', {
            nid: value.nid,
            checked: true,
          })
          break
        }
      }
    },
    // 全屏
    playFullscreen(id) {
      if (!screenfull.isEnabled) {
        this.$message({
          message: '浏览器不支持全屏',
          type: 'warning',
          showClose: true,
          duration: 3 * 1000,
        })
        return false
      }
      let div = document.getElementById(id)
      screenfull.toggle(div)
    },
    // 销毁视频播放
    destroyRtspNode() {
      this.srcArray.forEach((item, index) => {
        this.closeSrcRtspNode(index)
        // if (item.flowID) SDK.closeVideo(item.videoID, item.flowID)
      })
      this.closeMixRtspNode()
    },
    // 根据分辨率设置是否隐藏视频播放区
    resetHiddenVideos() {
      if (document.body.clientWidth > 1024) {
        this.hiddenVideos = false
      } else {
        this.hiddenVideos = true
      }
      window.onresize = () => {
        if (document.body.clientWidth > 1024) {
          this.hiddenVideos = false
        } else {
          this.hiddenVideos = true
        }
      }
    },
  },
  mounted() {
    this.resetHiddenVideos()
    window.addEventListener('beforeunload', this.destroyRtspNode)
  },
  beforeDestroy() {
    window.removeEventListener('beforeunload', this.destroyRtspNode)
  },
}
</script>

<style lang="scss" scoped>
@import '~@/assets/scss/video_plate.scss';
</style>
